<?php
/**
 * @author  Eddy <cumtsjh@163.com>
 */

namespace App\Model\Basic;

use Illuminate\Database\Eloquent\SoftDeletes;

class Entity extends Model
{
    use SoftDeletes;
    protected $table = \App\Utils\Enums\TableEnums::SYS_ENTITIES;
    const COMMENT_ENABLE = 1;
    const COMMENT_DISABLE = 0;

    const INTERNAL_YES = 1;
    const INTERNAL_NO = 0;

    const CONTENT_MANAGE_YES = 1;
    const CONTENT_MANAGE_NO = 0;

    //  模型类型 文档模型
    const ENTITY_TYPE_DOCUMENT = 'document';
    //  其他模型
    const ENTITY_TYPE_OTHER = 'other';

    protected $guarded = [];

    public static $listField = [
        'name' => '名称',
        'table_name' => '数据库表名',
        'description' => '描述',
    ];

    protected $appends = [
        'list_field_array',
        'entity_model_name'
    ];

    protected function getListFieldArrayAttribute()
    {
        if (isset($this->attributes['list_show_field']) && !empty($this->attributes['list_show_field'])) {
            $string = trim($this->attributes['list_show_field']);
            $data = explode("\n", $string);
            $list = [];
            foreach ($data as $key => $value) {
                $arr = explode('=', $value);
                $list[$arr[0]] = $arr[1];
            }
            return $list;
        }
        return [];
    }

    public function fields()
    {
        return $this->hasMany('App\Model\Basic\EntityField', 'entity_id');
    }

    /**
     * 限制查询外部模型
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeExternal($query)
    {
        return $query->where('is_internal', self::INTERNAL_NO);
    }

    /**
     *
     * @param $tableName
     * @return mixed
     */
    public function getEntityModelNameAttribute()
    {
        return str_replace('cms_document_', '', $this->attributes['table_name']);
    }
}
